package com.polaris.live.im.sfs.processor.impl

import com.lxj.xpopup.XPopup
import com.polaris.live.common.manager.CoroutineScopeManager
import com.polaris.live.common.util.JsonUtils
import com.polaris.live.common.util.ViewUtils
import com.polaris.live.dialog.PartyTaskDialog
import com.polaris.live.im.sfs.COMMAND_NOTICE_TASK_COMPLETE
import com.polaris.live.im.sfs.bean.pusher.NoticeTaskCompleteMessage
import com.polaris.live.im.sfs.bean.pusher.PusherNoticeMessage
import com.polaris.live.im.sfs.core.bean.DataArgument
import com.polaris.live.im.sfs.processor.AbstractMessageProcessor
import com.polaris.live.manager.LiveStateManager
import com.polaris.live.ui.game.GameUtils
import com.polaris.live.ui.party.PartyUserStateUtil
import com.polaris.live.ui.party.activity.PartyAnchorActivity
import com.polaris.live.ui.party.activity.game.PartyGameAnchorActivity
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/**
 * NoticeTaskMessageProcessor
 *
 * @author Created by 半仙 on 2024/3/13/013 10:57
 */
class NoticeTaskMessageProcessor : AbstractMessageProcessor() {

    override fun shouldProcess(type: Int, command: String): Boolean {
        return command == COMMAND_NOTICE_TASK_COMPLETE
    }

    override suspend fun handle(type: Int, command: String, argument: DataArgument) {
        val data = argument.getData<PusherNoticeMessage>() ?: return
        val message =
            JsonUtils.fromJson<NoticeTaskCompleteMessage>(data.content) ?: return

        withContext(CoroutineScopeManager.mainDispatcher) {
            val aliveTopActivity = ViewUtils.getAliveTopActivity() ?: return@withContext

            if (LiveStateManager.isCalling()
                || LiveStateManager.isLiving()
                || aliveTopActivity is PartyGameAnchorActivity
                || aliveTopActivity is PartyAnchorActivity
                || GameUtils.gameRun
                || PartyUserStateUtil.inTheGame || PartyUserStateUtil.inTheGameSeat || PartyUserStateUtil.inTheMaiSeat
            ) {
                return@withContext
            }

            CoroutineScopeManager.mainScope.launch {
                XPopup.Builder(aliveTopActivity)
                    .isDestroyOnDismiss(true)
                    .asCustom(PartyTaskDialog(aliveTopActivity, message))
                    .show()
            }
        }
    }
}